package com.ysl.netty;

import com.alibaba.fastjson.JSONObject;
import com.ysl.netty.server.MyServerInitializer;
import com.ysl.netty.webserver.WebServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 同时启动socket和websocket两个服务器
 */
@Component
public class NettyStart {

    @Value("${ysl.server.port}")
    private int port;
    @Value("${ysl.server.webport}")
    private int webport;

    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup workerGroup = new NioEventLoopGroup();

    //@PostConstruct
    public void start()
    {
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            ServerBootstrap webServerBootstrap = new ServerBootstrap();
            /*
                	所有的Handler() 都是针对bossGroup发挥作用
                	所有的childHandler() 都是针对workerGroup发挥作用，连接丢给workerGroup
                 	之后由childHandler对象对workerGroup这个Nio线程发挥作用
             */
            System.out.println("启动server");
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new MyServerInitializer());
            webServerBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new WebServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(port==0?8899:port).sync();
            ChannelFuture webChannelFuture = webServerBootstrap.bind(webport==0?8888:webport).sync();

            channelFuture.channel().closeFuture().sync();
            webChannelFuture.channel().closeFuture().sync();

        }
        catch (Exception ex)
        {

        }
        finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 销毁
     */
    //@PreDestroy
    public void destroy() {
        bossGroup.shutdownGracefully().syncUninterruptibly();
        workerGroup.shutdownGracefully().syncUninterruptibly();
    }

    public static void main(String[] args) {
        //DemoServer.start();
        //WebServer.start();
        //String msg="{\"type\":\"login\",\"userid\":\"120013\"}";
        //JSONObject json=JSONObject.parseObject(msg.toString());
        new NettyStart().start();
    }
}
